<template>
  <div class="chat-page">
    <van-nav-bar
      :title="doctorName"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="chatContent">
      <div class="message-list">
        <div
          v-for="msg in messages"
          :key="msg.id"
          class="message-item"
          :class="{ 'message-right': msg.fromUserId === userId }"
        >
          <van-image
            :src="msg.fromUserId === userId ? userAvatar : doctorAvatar"
            width="40"
            height="40"
            radius="20"
          />
          <div class="message-bubble">{{ msg.content }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <van-field
        v-model="inputMessage"
        placeholder="请输入内容"
        :border="false"
        @keypress.enter="sendMess"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendMess">发送</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getChatMessages, sendMessage } from '@/api/consultation'
import defaultAvatar from '@/assets/default-avatar.png'

const route = useRoute()
const router = useRouter()
const consultationId = route.query.consultationId
const doctorName = route.query.doctorName
const userId = ref('')
const userAvatar = ref(defaultAvatar)
const doctorAvatar = ref(defaultAvatar)

const messages = ref([])
const inputMessage = ref('')
const chatContent = ref(null)

// 加载聊天记录
const loadMessages = async () => {
  try {
    const { data } = await getChatMessages(consultationId)
    messages.value = data
    scrollToBottom()
  } catch (error) {
    showToast('获取聊天记录失败')
  }
}

// 发送消息
const sendMess = async () => {
  if (!inputMessage.value.trim()) {
    return
  }

  try {
    await sendMessage(consultationId, {
      content: inputMessage.value,
      type: 1 // 1-文本消息
    })

    messages.value.push({
      id: Date.now(),
      fromUserId: userId.value,
      content: inputMessage.value,
      createTime: new Date()
    })

    inputMessage.value = ''
    scrollToBottom()
  } catch (error) {
    showToast('发送失败')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight
    }
  })
}

onMounted(() => {
  loadMessages()
})
</script>

<style lang="scss" scoped>
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-top: 46px;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.message-list {
  .message-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16px;

    &.message-right {
      flex-direction: row-reverse;

      .message-bubble {
        margin: 0 12px 0 0;
        background: #07c160;
        color: #fff;
      }
    }
  }

  .message-bubble {
    max-width: 70%;
    padding: 8px 12px;
    background: #f7f7f7;
    border-radius: 4px;
    margin: 0 0 0 12px;
    word-break: break-all;
  }
}

.chat-input {
  padding: 8px;
  background: #fff;
  border-top: 1px solid #eee;

  :deep(.van-field__button) {
    margin-left: 8px;
  }
}
</style>
